package com.nightsoul.gradle.task;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;

import com.nightsoul.gradle.utils.FileUtils;

public class ClearCacheTask extends DefaultTask {
	private List<String> artifacts;
	private boolean clearSelf = true;
	private String metaBase;
	private String libBase;

	@TaskAction
	public void clearCache() throws Exception {
		if(artifacts!=null) {
			for(String artifact : artifacts) {
				clearArtifactCache(artifact);
			}
		}
		
		if(clearSelf) {
			String group = this.getProject().getGroup().toString();
			String name = this.getProject().getName();
			String version = this.getProject().getVersion().toString();
			String artifact = group + ":" + name + ":" + version;
			clearArtifactCache(artifact);
		}
	}

	private void clearArtifactCache(String artifact) throws IOException {
		String libPath = this.getArtifactLibPath(artifact);
		String metaPath = this.getArtifactMetaPath(artifact);
		FileUtils.deleteDirectory(new File(libPath));
		FileUtils.deleteDirectory(new File(metaPath));
	}

	public List<String> getArtifacts() {
		return artifacts;
	}

	public void setArtifacts(List<String> artifacts) {
		this.artifacts = artifacts;
	}

	public boolean isClearSelf() {
		return clearSelf;
	}
	public void setClearSelf(boolean clearSelf) {
		this.clearSelf = clearSelf;
	}
	public String getMetaBase() {
		if(this.metaBase==null) {
			File gradleUserHome = this.getProject().getGradle().getGradleUserHomeDir();
			StringBuilder metaBasePath = new StringBuilder(gradleUserHome.getAbsolutePath());
			metaBasePath.append(File.separator).append("caches").append(File.separator).append("modules-2")
				.append(File.separator).append("metadata-2.2").append(File.separator).append("descriptors");
			this.metaBase = metaBasePath.toString();
		}
		return metaBase;
	}

	public void setMetaBase(String metaBase) {
		this.metaBase = metaBase;
	}
	public String getLibBase() {
		if(libBase==null) {
			File gradleUserHome = this.getProject().getGradle().getGradleUserHomeDir();
			StringBuilder libBasePath = new StringBuilder(gradleUserHome.getAbsolutePath());
			libBasePath.append(File.separator).append("caches").append(File.separator).append("modules-2")
				.append(File.separator).append("files-2.1");
			this.libBase = libBasePath.toString();
		}
		return libBase;
	}

	public void setLibBase(String libBase) {
		this.libBase = libBase;
	}
	
	

	private String getArtifactLibPath(String artifact) {
		StringBuilder libPath = new StringBuilder(this.getLibBase());
		libPath.append(File.separator).append(artifact.replace(':', File.separatorChar));
		return libPath.toString();
	}
	private String getArtifactMetaPath(String artifact) {
		StringBuilder metaPath = new StringBuilder(this.getMetaBase());
		metaPath.append(File.separator).append(artifact.replace(':', File.separatorChar));
		return metaPath.toString();
	}
	
}
